package com.yitao.cms.service.overseasLogisticsInfo;

import com.querydsl.core.types.Order;
import com.querydsl.core.types.OrderSpecifier;
import com.skipper.base.bean.CommonStatus;
import com.skipper.base.bean.DataOutput;
import com.skipper.base.bean.PagedInput;
import com.skipper.base.bean.PagedOutput;
import com.skipper.base.common.excel.DataColumn;
import com.skipper.base.common.excel.DataTable;
import com.skipper.base.common.excel.ExcelConverter;
import com.skipper.base.data.querydsl.PredicateBuilder;
import com.skipper.base.json.JSON;
import com.skipper.base.json.JSONArray;
import com.skipper.base.json.JSONObject;
import com.skipper.base.service.GenericEntityService;
import com.yitao.client.model.order.MallOrderModel;
import com.yitao.cms.constant.UserSession;
import com.yitao.cms.dto.overseasLogistics.OverseasLogisticsInfoDto;
import com.yitao.cms.dto.overseasLogistics.OverseasLogisticsP1InfoDto;
import com.yitao.cms.dto.overseasLogistics.OverseasLogisticsP3InfoDto;
import com.yitao.cms.dto.overseasLogistics.OverseasProductInfoDto;
import com.yitao.cms.enums.OverseasLogisticsEnums;
import com.yitao.cms.model.operationUser.OperationUserCmsModel;
import com.yitao.cms.model.overseasLogistics.*;

import com.yitao.cms.service.order.CmsOrderService;
import com.yitao.cms.utils.*;
import com.yitao.cms.vo.overseasLogistics.TransferStatusCallbackVo;
import com.yitao.cms.vo.overseasLogistics.WarehouseCallbackVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: wwl
 * @Date: 2019/4/9 11:59
 * @Description:
 */
@Service
public class OverseasLogisticsInfoService extends GenericEntityService<OverseasLogisticsInfoModel, OverseasLogisticsInfoDto, QOverseasLogisticsInfoModel> {
    public OverseasLogisticsInfoService(EntityManager entityManager) {
        super(entityManager);
    }

    private BaseUtils base = BaseUtils.getInstance();
    @Autowired
    private OverseasLogisticsInfoService overseasLogisticsInfoService;
    @Autowired
    private CmsOrderService orderService;
    @Autowired
    private OverseasProductInfoService overseasProductInfoService;
    @Autowired
    private OverseasLogisticsErrorService overseasLogisticsErrorService;
    @Value("${fastdfs.head}")
    private String headUrl;
    @Value("${overseals_p1Url}")
    private String p1Url;
    @Value("${overseals_p3Url}")
    private String p3Url;
    @Value("${overseals_username}")
    private String username;
    @Value("${overseals_password}")
    private String password;
   // String url = "http://t.yyox.com:1010/createOrder";
    /*private final String p1Url ="http://api.yyox.com/createInventory";
    private final String p3Url ="http://api.yyox.com/createOrder";
    private final String username ="poyyox@yyox.com";
    private final String password ="8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92";*/

    @Transactional
    public DataOutput dateImport(MultipartFile file, OperationUserCmsModel userSession) {
        List<OverseasLogisticsInfoDto> overseasLogisticsInfoModelList = ExcelExportUtil.importDate(file, userSession);
        List<OverseasLogisticsInfoModel> listOv = new ArrayList<>();//主信息
        List<OverseasProductInfoModel> productInfoModelList = new ArrayList<>();//产品信息
        List<String> overseaExpressNoList = new ArrayList<>();//快递单号
        Map<String, String> tanksNoList = new HashMap<>();//和箱箱号
        if (overseasLogisticsInfoModelList != null && overseasLogisticsInfoModelList.size() > 0) {
            for (int i = 0; i < overseasLogisticsInfoModelList.size(); i++) {
                //必填字段非空判断
                logger.info("请求参数i:{}", JSON.toJSONString(overseasLogisticsInfoModelList.get(i)));
                if (base.parametersIsBlank(overseasLogisticsInfoModelList.get(i).getOverseaExpressNo(),//境外快递单号
                        overseasLogisticsInfoModelList.get(i).getRoller(),//Roller
                        overseasLogisticsInfoModelList.get(i).getOrderSource(),//订单来源
                        overseasLogisticsInfoModelList.get(i).getCnyName(),//商品中文名称
                        overseasLogisticsInfoModelList.get(i).getCategory(),//分类
                        overseasLogisticsInfoModelList.get(i).getBrand(),//品牌
                        overseasLogisticsInfoModelList.get(i).getPriceUnit(),//币种
                        overseasLogisticsInfoModelList.get(i).getDeclaredPrice(),//原币单价
                        overseasLogisticsInfoModelList.get(i).getCount(),//数量
                        overseasLogisticsInfoModelList.get(i).getLogisticsProviders(),//物流服务商
                        overseasLogisticsInfoModelList.get(i).getBuyerName(),//买家姓名
                        overseasLogisticsInfoModelList.get(i).getBuyerIdcard(),//买家身份证号码
                        overseasLogisticsInfoModelList.get(i).getBuyerMobile(),//买家手机号码
                        overseasLogisticsInfoModelList.get(i).getBuyerProvince(),//买家省份
                        overseasLogisticsInfoModelList.get(i).getBuyerCity(),//买家城市
                        overseasLogisticsInfoModelList.get(i).getBuyerDistrict(),//买家区
                        overseasLogisticsInfoModelList.get(i).getBuyerAdress()//买家详细地址
                )
                ) {

                    return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "请确认:境外快递单号,Roller,订单来源,商品中文名称,分类,品牌,币种,原币单价,数量,物流服务商," +
                            "买家姓名,买家身份证号码,买家手机号码,买家省份,买家城市,买家区,买家详细地址等信息不能为空!");
                }
                //境外快递单号验证
                List<String> list = overseasLogisticsInfoService.findOverseaExpressNo(overseasLogisticsInfoModelList.get(i).getOverseaExpressNo());
                if (list != null && list.size() > 0) {
                    return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "快递单号:" + overseasLogisticsInfoModelList.get(i).getOverseaExpressNo() + "重复!");
                }
               //有拆箱操作是合箱箱号不能为空
                if (StringUtils.isBlank(overseasLogisticsInfoModelList.get(i).getTanksNo())){
                    return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "合箱箱号不能为空!");
                }
                //身份证号码验证
                String card = overseasLogisticsInfoModelList.get(i).getBuyerIdcard();
                if (!card.matches("^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$")) {
                    return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "买家身份证号码有误!");
                }
                //手机号校验
                if (!overseasLogisticsInfoModelList.get(i).getBuyerMobile().matches("^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\\d{8}$")) {
                    return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "买家手机号码有误!");
                }
                //内部订单号
                String customerRefNo = overseasLogisticsInfoModelList.get(i).getCustomerRefNo();
                if (StringUtils.isNotBlank(customerRefNo)) {
                    if (overseasLogisticsInfoService.findOrderNo(customerRefNo)) {//表示重复
                        return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "内部订单号" + customerRefNo + "重复!");
                    }
                }
                //合箱箱号处理
                if (overseasLogisticsInfoModelList.get(i).getTanksNo() != null && tanksNoList.get(overseasLogisticsInfoModelList.get(i).getTanksNo()) != null) {
                    overseasLogisticsInfoModelList.get(i).setTanksNo(tanksNoList.get(overseasLogisticsInfoModelList.get(i).getTanksNo()));
                } else {
                    String tanksNo = overseasLogisticsInfoModelList.get(i).getTanksNo() + "-" + UUID.randomUUID().toString();
                    tanksNoList.put(overseasLogisticsInfoModelList.get(i).getTanksNo(), tanksNo);
                    overseasLogisticsInfoModelList.get(i).setTanksNo(tanksNo);

                }
                //判断快递单号是否重复添整理主信息
                if (!overseaExpressNoList.contains(overseasLogisticsInfoModelList.get(i).getOverseaExpressNo())) {
                    overseaExpressNoList.add(overseasLogisticsInfoModelList.get(i).getOverseaExpressNo());
                    listOv.add(convertDtoToEntity(overseasLogisticsInfoModelList.get(i)));
                }
                OverseasProductInfoModel overseasProductInfoModel = new OverseasProductInfoModel();
                BeanUtils.copyProperties(overseasLogisticsInfoModelList.get(i), overseasProductInfoModel);
                overseasProductInfoModel.setCreateBy(userSession.getId());
                productInfoModelList.add(overseasProductInfoModel);
            }
            List<OverseasProductInfoModel> list = overseasProductInfoService.insertProductInfo(productInfoModelList);
            if (list != null && list.size() > 0) {
                List<OverseasLogisticsInfoModel> overseasLogisticsInfoModelList1 = repository.save(listOv);
                //调用接口更新状态
                this.httpShipments();
                this.createOrder();
                return new DataOutput(overseasLogisticsInfoModelList1);
            }
        }
        return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "导入的数据不能为空!");

    }

    /**
     * 查询列表
     *
     * @param overseaExpressNo
     * @param buyerName
     * @param buyerIdCard
     * @param p2Status
     * @param p4Status
     * @param staDate
     * @param endDate
     * @param pagedInput
     * @return
     */
    public PagedOutput findList(String overseaExpressNo, String orderSource, String customerRefNo, String logisticsProviders, String buyerName, String buyerIdCard, Integer p2Status, Integer p4Status, String staDate, String endDate, PagedInput pagedInput) {


        List<String> overseaExpressNoList = new ArrayList<>();
        List<String> customerRefNoList = new ArrayList<>();
        if (StringUtils.isNotBlank(overseaExpressNo)) {
            if (overseaExpressNo.contains(",")) {
                overseaExpressNoList = Arrays.asList(overseaExpressNo.split(","));
            } else {
                overseaExpressNoList.add(overseaExpressNo);
            }
        }
        if (StringUtils.isNotBlank(customerRefNo)) {
            if (customerRefNo.contains(",")) {
                customerRefNoList = Arrays.asList(customerRefNo.split(","));
            } else {
                customerRefNoList.add(customerRefNo);
            }
        }
        final List<String> noList = overseaExpressNoList;
        final List<String> customerRefList = customerRefNoList;
        Date staDate2 = null;
        Date endDate2 = null;
        if (StringUtils.isNotBlank(staDate)) {
            staDate2 = DatetimeUtil.stringToDate(staDate);
        }
        if (StringUtils.isNotBlank(endDate)) {
            endDate2 = DatetimeUtil.stringToDate(endDate + " 23:59:59");
        }
        final Date staDate1 = endDate2;
        final Date endDate1 = staDate2;
        PagedOutput<OverseasLogisticsInfoModel> overseasLogisticsInfoModelPagedOutput
                = repository.pagingList(PredicateBuilder.conjunction()
                .ifHasTextThenAnd(overseaExpressNo, () -> Q.overseaExpressNo.in(noList))
                .ifHasTextThenAnd(orderSource, () -> Q.orderSource.eq(orderSource))
                .ifHasTextThenAnd(customerRefNo, () -> Q.customerRefNo.in(customerRefList))
                .ifHasTextThenAnd(logisticsProviders, () -> Q.logisticsProviders.eq(logisticsProviders))
                .ifHasTextThenAnd(buyerName, () -> Q.buyerName.eq(buyerName))
                .ifHasTextThenAnd(buyerIdCard, () -> Q.buyerIdcard.eq(buyerIdCard))
                .ifNotNullThenAnd(p2Status, () -> Q.p2Status.eq(p2Status))
                .ifNotNullThenAnd(p4Status, () -> Q.p4Status.eq(p4Status))
                .ifNotNullThenBetween(staDate1, endDate1, Q.createTime)
                .and(()->Q.isDelete.eq(false))
                .get(), pagedInput, new OrderSpecifier<>(Order.DESC, Q.createTime)
        );
        List<OverseasLogisticsInfoDto> list = overseasLogisticsInfoModelPagedOutput.getData().stream().map(it -> {
            OverseasLogisticsInfoDto overseasLogisticsInfoDto = new OverseasLogisticsInfoDto();
            BeanUtils.copyProperties(it, overseasLogisticsInfoDto);
            List<OverseasProductInfoDto> list1 = overseasProductInfoService.findProductByNo(it.getOverseaExpressNo());
            if (list1 != null && list1.size() > 0) {
                overseasLogisticsInfoDto.setGoodsList(list1);
                overseasLogisticsInfoDto.setPriceUnit(list1.get(0).getPriceUnit());//单位
                overseasLogisticsInfoDto.setInlandExpressId(OverseasLogisticsEnums.EXPRESSCODE.getDescByCode(it.getInlandExpressId())); // 格式化快递公司名称
                Integer productCount = list1.stream().map(OverseasProductInfoDto::getCount).reduce(Integer::sum).get();
                if (productCount != null) {//产品数量
                    overseasLogisticsInfoDto.setProductCount(productCount);
                }
                Double totalMoney = new Double(0);
                for (int i=0;i<list1.size();i++){
                    Double money = new Double(0);
                    if (list1.get(i)!=null && StringUtils.isNotBlank(list1.get(i).getDeclaredPrice()) && list1.get(i).getCount()!=null){
                        money=Double.valueOf(list1.get(i).getDeclaredPrice())*list1.get(i).getCount();
                    }
                    totalMoney = totalMoney+money;
                }
                overseasLogisticsInfoDto.setTotalMoney(totalMoney);
                overseasLogisticsInfoDto.setSkuCount(list1.size());
            }
            return overseasLogisticsInfoDto;
        }).collect(Collectors.toList());
        return new PagedOutput(pagedInput, overseasLogisticsInfoModelPagedOutput.getTotalElements(), list);
    }

    /**
     * 导出产品数据查询
     *
     * @param overseaExpressNo
     * @param buyerName
     * @param buyerIdCard
     * @param p2Status
     * @param p4Status
     * @param staDate
     * @param endDate
     */
    public void findProductListExport(HttpServletRequest request, HttpServletResponse response, String overseaExpressNo, String orderSource, String customerRefNo, String logisticsProviders, String buyerName, String buyerIdCard,
                                      Integer p2Status, Integer p4Status, String staDate, String endDate) {

        List<String> overseaExpressNoList = new ArrayList<>();
        List<String> customerRefNoList = new ArrayList<>();
        if (StringUtils.isNotBlank(overseaExpressNo)) {
            if (overseaExpressNo.contains(",")) {
                overseaExpressNoList = Arrays.asList(overseaExpressNo.split(","));
            } else {
                overseaExpressNoList.add(overseaExpressNo);
            }
        }
        if (StringUtils.isNotBlank(customerRefNo)) {
            if (customerRefNo.contains(",")) {
                customerRefNoList = Arrays.asList(customerRefNo.split(","));
            } else {
                customerRefNoList.add(customerRefNo);
            }
        }
        final List<String> noList = overseaExpressNoList;
        final List<String> customerRefList = customerRefNoList;
        Date staDate2 = null;
        Date endDate2 = null;
        if (StringUtils.isNotBlank(staDate)) {
            staDate2 = DatetimeUtil.stringToDate(staDate);
        }
        if (StringUtils.isNotBlank(endDate)) {
            endDate2 = DatetimeUtil.stringToDate(endDate + " 23:59:59");
        }
        final Date staDate1 = endDate2;
        final Date endDate1 = staDate2;

        QOverseasProductInfoModel qOverseasProductInfoModel = QOverseasProductInfoModel.overseasProductInfoModel;
        List<OverseasProductInfoModel> listPro = queryFactory.select(qOverseasProductInfoModel).from(qOverseasProductInfoModel)
                .leftJoin(Q).on(qOverseasProductInfoModel.overseaExpressNo.eq(Q.overseaExpressNo)).where(
                        PredicateBuilder.conjunction()
                                .ifHasTextThenAnd(overseaExpressNo, () -> Q.overseaExpressNo.in(noList))
                                .ifHasTextThenAnd(orderSource, () -> Q.orderSource.eq(orderSource))
                                .ifHasTextThenAnd(customerRefNo, () -> Q.customerRefNo.in(customerRefList))
                                .ifHasTextThenAnd(logisticsProviders, () -> Q.logisticsProviders.eq(logisticsProviders))
                                .ifHasTextThenAnd(buyerName, () -> Q.buyerName.eq(buyerName))
                                .ifHasTextThenAnd(buyerIdCard, () -> Q.buyerIdcard.eq(buyerIdCard))
                                .ifNotNullThenAnd(p2Status, () -> Q.p2Status.eq(p2Status))
                                .ifNotNullThenAnd(p4Status, () -> Q.p4Status.eq(p4Status))
                                .and(()->Q.isDelete.eq(false))
                                .ifNotNullThenBetween(staDate1, endDate1, Q.clientCreateOrderDate).get()
                ).fetch();

        List<OverseasLogisticsInfoDto> list = listPro.stream().map(it -> {
            OverseasLogisticsInfoDto overseasLogisticsInfoDto = new OverseasLogisticsInfoDto();
            BeanUtils.copyProperties(it, overseasLogisticsInfoDto);
            OverseasLogisticsInfoModel overseasLogisticsInfoModel = queryFactory.select(Q).from(Q).where(Q.overseaExpressNo.eq(it.getOverseaExpressNo())).fetchFirst();
            if (overseasLogisticsInfoModel != null) {
                BeanUtils.copyProperties(overseasLogisticsInfoModel, overseasLogisticsInfoDto);
            }
            return overseasLogisticsInfoDto;
        }).collect(Collectors.toList());
        JSONArray jsonArray = new JSONArray();
        jsonArray.fluentAddAll(list);
        overseasLogisticsInfoService.downloadProductExcel(request, response, jsonArray);
    }

    /**
     * 导出产品数据查询
     *
     * @param overseaExpressNo
     * @param buyerName
     * @param buyerIdCard
     * @param p2Status
     * @param p4Status
     * @param staDate
     * @param endDate
     */
    public void findListExport(HttpServletRequest request, HttpServletResponse response, String overseaExpressNo, String orderSource, String customerRefNo, String logisticsProviders, String buyerName, String buyerIdCard,
                               Integer p2Status, Integer p4Status, String staDate, String endDate) {

        List<String> overseaExpressNoList = new ArrayList<>();
        List<String> customerRefNoList = new ArrayList<>();
        if (StringUtils.isNotBlank(overseaExpressNo)) {
            if (overseaExpressNo.contains(",")) {
                overseaExpressNoList = Arrays.asList(overseaExpressNo.split(","));
            } else {
                overseaExpressNoList.add(overseaExpressNo);
            }
        }
        if (StringUtils.isNotBlank(customerRefNo)) {
            if (customerRefNo.contains(",")) {
                customerRefNoList = Arrays.asList(customerRefNo.split(","));
            } else {
                customerRefNoList.add(customerRefNo);
            }
        }
        final List<String> noList = overseaExpressNoList;
        final List<String> customerRefList = customerRefNoList;
        Date staDate2 = null;
        Date endDate2 = null;
        if (StringUtils.isNotBlank(staDate)) {
            staDate2 = DatetimeUtil.stringToDate(staDate);
        }
        if (StringUtils.isNotBlank(endDate)) {
            endDate2 = DatetimeUtil.stringToDate(endDate + " 23:59:59");
        }
        final Date staDate1 = endDate2;
        final Date endDate1 = staDate2;

        List<OverseasLogisticsInfoModel> overseasLogisticsInfoModelList
                = repository.findAll(PredicateBuilder.conjunction()
                .ifHasTextThenAnd(overseaExpressNo, () -> Q.overseaExpressNo.in(noList))
                .ifHasTextThenAnd(orderSource, () -> Q.orderSource.eq(orderSource))
                .ifHasTextThenAnd(customerRefNo, () -> Q.customerRefNo.in(customerRefList))
                .ifHasTextThenAnd(logisticsProviders, () -> Q.logisticsProviders.eq(logisticsProviders))
                .ifHasTextThenAnd(buyerName, () -> Q.buyerName.eq(buyerName))
                .ifHasTextThenAnd(buyerIdCard, () -> Q.buyerIdcard.eq(buyerIdCard))
                .ifNotNullThenAnd(p2Status, () -> Q.p2Status.eq(p2Status))
                .ifNotNullThenAnd(p4Status, () -> Q.p4Status.eq(p4Status))
                .and(()->Q.isDelete.eq(false))
                .ifNotNullThenBetween(staDate1, endDate1, Q.createTime).get());

        List<OverseasLogisticsInfoDto> list = overseasLogisticsInfoModelList.stream().map(it -> {
            OverseasLogisticsInfoDto overseasLogisticsInfoDto = new OverseasLogisticsInfoDto();
            BeanUtils.copyProperties(it, overseasLogisticsInfoDto);
            List<OverseasProductInfoDto> list1 = overseasProductInfoService.findProductByNo(it.getOverseaExpressNo());
            if (list1 != null && list1.size() > 0) {
                overseasLogisticsInfoDto.setGoodsList(list1);
                overseasLogisticsInfoDto.setPriceUnit(list1.get(0).getPriceUnit());//单位
                Integer productCount = list1.stream().map(OverseasProductInfoDto::getCount).reduce(Integer::sum).get();
                if (productCount != null) {//产品数量
                    overseasLogisticsInfoDto.setProductCount(productCount);
                }
                Double totalMoney = new Double(0);
                for (int i=0;i<list1.size();i++){
                    Double money = new Double(0);
                    if (list1.get(i)!=null && StringUtils.isNotBlank(list1.get(i).getDeclaredPrice()) && list1.get(i).getCount()!=null){
                        money=Double.valueOf(list1.get(i).getDeclaredPrice())*list1.get(i).getCount();
                    }
                    totalMoney = totalMoney+money;
                }
                overseasLogisticsInfoDto.setTotalMoney(totalMoney);
                overseasLogisticsInfoDto.setSkuCount(list1.size());
            }
            return overseasLogisticsInfoDto;
        }).collect(Collectors.toList());
        JSONArray jsonArray = new JSONArray();
        jsonArray.fluentAddAll(list);
        overseasLogisticsInfoService.downloadExcel(request, response, jsonArray);
    }

    /**
     * 数据下载
     */

    public void downloadExcel(HttpServletRequest request, HttpServletResponse response, JSONArray jsonArray) {
        String nowDate = DateUtils.nowDate("yyyyMMddHHmmss");
        //excel文件名
        String fileName = "境外物流信息" + nowDate + ".xlsx";
        //sheet名
        String sheetName = "sheet1";
        //响应到客户端
        try {
            this.setResponseHeader(request, response, fileName);
            OutputStream os = response.getOutputStream();
            ExcelConverter excelConverter = ExcelConverter.forXlsx();
            DataTable dataTable = new DataTable(sheetName);
            List<DataColumn> columns = new ArrayList<>();
            columns.add(new DataColumn("overseaExpressNo", "境外快递单号"));
            columns.add(new DataColumn("merchantOrderNo", "电商平台订单号"));
            columns.add(new DataColumn("roller", "买手姓名"));
            columns.add(new DataColumn("clientCreateOrderDateStr", "电商平台下单时间"));
            columns.add(new DataColumn("orderSource", "订单来源"));
            columns.add(new DataColumn("customerRefNo", "内部订单号"));
            columns.add(new DataColumn("tanksNo", "合箱箱号"));
            columns.add(new DataColumn("skuCount", "SKU数量"));
            columns.add(new DataColumn("productCount", "产品总数"));
            columns.add(new DataColumn("totalMoney", "总金额"));
          /*  columns.add(new DataColumn("name", "商品原始名"));
            columns.add(new DataColumn("cnyName", "商品中文名"));
            columns.add(new DataColumn("skuId", "电商平台商品id"));
            columns.add(new DataColumn("upc", "商品UPC码"));
            columns.add(new DataColumn("category", "商品分类描述"));
            columns.add(new DataColumn("brand", "商品品牌"));
            columns.add(new DataColumn("spec", "商品规格"));*/
           /* columns.add(new DataColumn("priceUnit", "币种"));
            columns.add(new DataColumn("declaredPrice", "原币单价"));
            columns.add(new DataColumn("count", "商品数量"));*/
            columns.add(new DataColumn("logisticsProviders", "物流服务商"));
            columns.add(new DataColumn("transferId", "物流服务商单号"));
            columns.add(new DataColumn("senderName", "发货人姓名"));
            columns.add(new DataColumn("senderDetailaddress", "国内发件人地址"));
            columns.add(new DataColumn("senderMobile", "国内发件人电话"));
            columns.add(new DataColumn("buyerName", "买家(收货人)姓名"));
            columns.add(new DataColumn("buyerIdcard", "买家(收货人)身份证号码"));
            columns.add(new DataColumn("buyerMobile", "买家(收货人)手机号码"));
            columns.add(new DataColumn("buyerProvince", "买家(收货人)省份"));
            columns.add(new DataColumn("buyerCity", "买家(收货人)城市"));
            columns.add(new DataColumn("buyerDistrict", "买家(收货人)行政区"));
            columns.add(new DataColumn("buyerAdress", "买家(收货人)详细地址"));
            columns.add(new DataColumn("buyerZipcode", "买家邮编"));
            columns.add(new DataColumn("inlandExpressId", "国内快递"));
            columns.add(new DataColumn("inlandExpressNo", "国内运单号"));
            columns.add(new DataColumn("p2StatusStr", "入库状态"));
            columns.add(new DataColumn("p4StatusStr", "发货状态"));
            columns.add(new DataColumn("message", "备注"));
            columns.add(new DataColumn("overseaInTimeStr", "转运仓入库时间"));
            columns.add(new DataColumn("overseaOutTimeStr", "出库时间"));
            columns.add(new DataColumn("inlandInTimeStr", "抵达国内时间"));
            columns.add(new DataColumn("inlandOutTimeStr", "已转国内快递时间"));
            columns.add(new DataColumn("buyerSignTimeStr", "用户签收时间"));
            dataTable.addColumns(columns);
            excelConverter.export(os, dataTable, jsonArray);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 数据下载
     */

    public void downloadProductExcel(HttpServletRequest request, HttpServletResponse response, JSONArray jsonArray) {
        String nowDate = DateUtils.nowDate("yyyyMMddHHmmss");
        //excel文件名
        String fileName = "境外物流详情信息" + nowDate + ".xlsx";
        //sheet名
        String sheetName = "sheet1";
        //响应到客户端
        try {
            this.setResponseHeader(request, response, fileName);
            OutputStream os = response.getOutputStream();
            ExcelConverter excelConverter = ExcelConverter.forXlsx();
            DataTable dataTable = new DataTable(sheetName);
            List<DataColumn> columns = new ArrayList<>();
            columns.add(new DataColumn("overseaExpressNo", "境外快递单号"));
            columns.add(new DataColumn("merchantOrderNo", "电商平台订单号"));
            columns.add(new DataColumn("roller", "买手姓名"));
            columns.add(new DataColumn("clientCreateOrderDateStr", "电商平台下单时间"));
            columns.add(new DataColumn("orderSource", "订单来源"));
            columns.add(new DataColumn("customerRefNo", "内部订单号"));
            columns.add(new DataColumn("tanksNo", "合箱箱号"));
            columns.add(new DataColumn("name", "商品原始名"));
            columns.add(new DataColumn("cnyName", "商品中文名"));
            columns.add(new DataColumn("skuId", "电商平台商品id"));
            columns.add(new DataColumn("upc", "商品UPC码"));
            columns.add(new DataColumn("category", "商品分类描述"));
            columns.add(new DataColumn("brand", "商品品牌"));
            columns.add(new DataColumn("spec", "商品规格"));
            columns.add(new DataColumn("priceUnit", "币种"));
            columns.add(new DataColumn("declaredPrice", "原币单价"));
            columns.add(new DataColumn("count", "商品数量"));
            columns.add(new DataColumn("logisticsProviders", "物流服务商"));
            columns.add(new DataColumn("transferId", "物流服务商单号"));
            columns.add(new DataColumn("senderName", "发货人姓名"));
            columns.add(new DataColumn("senderDetailaddress", "国内发件人地址"));
            columns.add(new DataColumn("senderMobile", "国内发件人电话"));
            columns.add(new DataColumn("buyerName", "买家(收货人)姓名"));
            columns.add(new DataColumn("buyerIdcard", "买家(收货人)身份证号码"));
            columns.add(new DataColumn("buyerMobile", "买家(收货人)手机号码"));
            columns.add(new DataColumn("buyerProvince", "买家(收货人)省份"));
            columns.add(new DataColumn("buyerCity", "买家(收货人)城市"));
            columns.add(new DataColumn("buyerDistrict", "买家(收货人)行政区"));
            columns.add(new DataColumn("buyerAdress", "买家(收货人)详细地址"));
            columns.add(new DataColumn("buyerZipcode", "买家邮编"));
            columns.add(new DataColumn("inlandExpressId", "国内快递"));
            columns.add(new DataColumn("inlandExpressNo", "国内运单号"));
            columns.add(new DataColumn("p2StatusStr", "入库状态"));
            columns.add(new DataColumn("p4StatusStr", "发货状态"));
            columns.add(new DataColumn("message", "备注"));
            columns.add(new DataColumn("overseaInTimeStr", "转运仓入库时间"));
            columns.add(new DataColumn("overseaOutTimeStr", "出库时间"));
            columns.add(new DataColumn("inlandInTimeStr", "抵达国内时间"));
            columns.add(new DataColumn("inlandOutTimeStr", "已转国内快递时间"));
            columns.add(new DataColumn("buyerSignTimeStr", "用户签收时间"));
            dataTable.addColumns(columns);
            excelConverter.export(os, dataTable, jsonArray);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件下载
     *
     * @param request
     * @param response
     * @param fileName
     */
    private void setResponseHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.ms-excel"); // 保存为excel
            response.setHeader("Content-Disposition", "attachment;" + ExcelExportUtil.getFileName(request, fileName));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 修改身份证图片信息
     *
     * @param request
     * @param id
     * @param buyerIdcardFrontend
     * @param buyerIdcardBackend
     * @return
     */
    @Transactional
    public DataOutput updateIdImage(HttpServletRequest request, String id, String buyerIdcardFrontend, String buyerIdcardBackend) {
        OperationUserCmsModel operationUserCmsModel = UserSession.getUserSession(request);
        if (operationUserCmsModel == null) {
            return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "请重新登录!");
        }
        if (StringUtils.isNotBlank(id)) {
            OverseasLogisticsInfoModel overseasLogisticsInfoModel = repository.findById(id);
            if (overseasLogisticsInfoModel != null) {
                int result = repository.updateByWhere(Q.id.eq(id), it ->
                        it.set(Q.buyerIdcardFrontend, buyerIdcardFrontend)
                                .set(Q.buyerIdcardBackend, buyerIdcardBackend)
                                .set(Q.lastUpdateTime, new Date()));
                if (result > 0) {
                    return new DataOutput(CommonStatus.SUCCESS);
                }
            }
        }
        return new DataOutput(CommonStatus.BAD_REQUEST);
    }

    /**
     * 查询数据详情
     *
     * @param id
     * @return
     */
    public DataOutput findInfById(String id) {
        if (StringUtils.isNotBlank(id)) {
            OverseasLogisticsInfoDto overseasLogisticsInfoDto = new OverseasLogisticsInfoDto();
            OverseasLogisticsInfoModel overseasLogisticsInfoModel = repository.findById(id);
            if (overseasLogisticsInfoModel != null && overseasLogisticsInfoModel.getOverseaExpressNo() != null) {
                BeanUtils.copyProperties(overseasLogisticsInfoModel, overseasLogisticsInfoDto);
                List<OverseasProductInfoDto> list = overseasProductInfoService.findProductByNo(overseasLogisticsInfoModel.getOverseaExpressNo());
                overseasLogisticsInfoDto.setGoodsList(list);
                return new DataOutput(overseasLogisticsInfoDto);
            }
            return new DataOutput(CommonStatus.SUCCESS);
        }
        return new DataOutput(CommonStatus.BAD_REQUEST);

    }

    /**
     * 查询180天内的境外快递单号
     *
     * @return
     */
    public List<String> findOverseaExpressNo(String code) {
        List<String> list = repository.findAll(Q.createTime.between(DateUtils.getPastDate(180), new Date())
                .and(Q.isDelete.eq(false))
                .and(Q.overseaExpressNo.eq(code)))
                .stream().map(it -> it.getOverseaExpressNo()).collect(Collectors.toList());
        return list;
    }

    /**
     * 内部订单号查询(true表示重复)
     */
    public Boolean findOrderNo(String customerRefNo) {
        List<OverseasLogisticsInfoModel> orderCode = repository.findAll(Q.isDelete.eq(false).and(Q.customerRefNo.eq(customerRefNo)));
        if (orderCode != null && orderCode.size() > 0) {
            return true;
        } else {
            List<MallOrderModel> list = orderService.findOrderInfoByOrderNo(customerRefNo);
            if (list != null && list.size() > 0) {
                return true;
            }

        }
        return false;
    }

    /**
     * P1入库预报接口
     */
    public void httpShipments() {
        /*String url = "http://t.yyox.com:1010/createInventory";*/
        List<OverseasLogisticsP1InfoDto> list = repository.findAll(Q.isDelete.eq(false).and(Q.p2Status.eq(OverseasLogisticsEnums.p2Status.FORECAST_NO.getCode())))
                .stream().map(it -> {
                    OverseasLogisticsP1InfoDto overseasLogisticsP1InfoDto = new OverseasLogisticsP1InfoDto();
                    BeanUtils.copyProperties(it, overseasLogisticsP1InfoDto);
                    overseasLogisticsP1InfoDto.setWareHouseId("ORB");
                    overseasLogisticsP1InfoDto.setUsername(username);
                    overseasLogisticsP1InfoDto.setPassword(password);
                    List<OverseasProductInfoDto> productInfoDtoList = overseasProductInfoService.findProductByNo(it.getOverseaExpressNo());
                    if (productInfoDtoList != null && productInfoDtoList.size() > 0) {
                        overseasLogisticsP1InfoDto.setGoodsList(productInfoDtoList);
                    }
                    return overseasLogisticsP1InfoDto;
                }).collect(Collectors.toList());
        JSONObject jo = new JSONObject();
        //组装发送数据
        for (int i = 0; i < list.size(); i++) {
            JSONObject jso = new JSONObject();
            jso.put("oversea_express_no", list.get(i).getOverseaExpressNo());
            jso.put("ware_house_id", "ORB");
            jso.put("merchant_order_no", list.get(i).getMerchantOrderNo());
            jso.put("value_added", new JSONArray());
            jso.put("username", username);
            jso.put("password", password);
            if (list.get(i).getGoodsList() != null && list.get(i).getGoodsList().size() > 0) {
                JSONArray jsonArray = new JSONArray();
                for (int j = 0; j < list.get(i).getGoodsList().size(); j++) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("sku_id", list.get(i).getGoodsList().get(j).getSkuId());
                    jsonObject.put("upc", list.get(i).getGoodsList().get(j).getUpc());
                    jsonObject.put("name", list.get(i).getGoodsList().get(j).getName());
                    jsonObject.put("cny_name", list.get(i).getGoodsList().get(j).getCnyName());
                    jsonObject.put("category", list.get(i).getGoodsList().get(j).getCategory());
                    jsonObject.put("brand", list.get(i).getGoodsList().get(j).getBrand());
                    jsonObject.put("spec", list.get(i).getGoodsList().get(j).getSpec());
                    jsonObject.put("price_unit", list.get(i).getGoodsList().get(j).getPriceUnit());
                    jsonObject.put("declared_price", list.get(i).getGoodsList().get(j).getDeclaredPrice());
                    jsonObject.put("count", list.get(i).getGoodsList().get(j).getCount());
                    jsonArray.add(jsonObject);
                }
                jso.put("goods_list", jsonArray);
            }
            jo.put("param", jso);
            logger.info("请求参数：{}",JSON.toJSONString(jo));
            String result = null;
            JSONObject jsonObject = null;
            try {
                result = HttpUtil.doRequestPostString(JSON.toJSONString(jo), p1Url);
                if (StringUtils.isNotBlank(result)){
                    jsonObject = JSON.parseObject(result);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (jsonObject != null && jsonObject.get("code").equals(0)) {
                this.updateP2Status(list.get(i).getOverseaExpressNo(), OverseasLogisticsEnums.p2Status.FORECAST_SUCCESS.getCode());
                // TODO 如果异常表存在这个单号，将这个运单号是否处理状态修改为已处理
                logger.info("list.get(i).getOverseaExpressNo()");
                overseasLogisticsErrorService.updateHandingStatusByOverseaExpressNo(list.get(i).getOverseaExpressNo());
            }
            logger.info("返回结果:{}", result);
        }
    }

    /**
     * P1入库预报接口
     */
    public DataOutput httpShipmentsById(String id) {
        //String url = "http://t.yyox.com:1010/createInventory";
        OverseasLogisticsInfoModel overseasLogisticsInfoModel = repository.findById(id);
        OverseasLogisticsP1InfoDto overseasLogisticsP1InfoDto = new OverseasLogisticsP1InfoDto();
        BeanUtils.copyProperties(overseasLogisticsInfoModel, overseasLogisticsP1InfoDto);
        overseasLogisticsP1InfoDto.setWareHouseId("ORB");
        overseasLogisticsP1InfoDto.setUsername(username);
        overseasLogisticsP1InfoDto.setPassword(password);
        List<OverseasProductInfoDto> productInfoDtoList = overseasProductInfoService.findProductByNo(overseasLogisticsInfoModel.getOverseaExpressNo());
        if (productInfoDtoList != null && productInfoDtoList.size() > 0) {
            overseasLogisticsP1InfoDto.setGoodsList(productInfoDtoList);
        }
        JSONObject jo = new JSONObject();
        //组装发送数据

        JSONObject jso = new JSONObject();
        jso.put("oversea_express_no", overseasLogisticsP1InfoDto.getOverseaExpressNo());
        jso.put("ware_house_id", "ORB");
        jso.put("merchant_order_no", overseasLogisticsP1InfoDto.getMerchantOrderNo());
        jso.put("value_added", new JSONArray());
        jso.put("username", username);
        jso.put("password", password);
        if (overseasLogisticsP1InfoDto.getGoodsList() != null && overseasLogisticsP1InfoDto.getGoodsList().size() > 0) {
            JSONArray jsonArray = new JSONArray();
            for (int j = 0; j < overseasLogisticsP1InfoDto.getGoodsList().size(); j++) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("sku_id", overseasLogisticsP1InfoDto.getGoodsList().get(j).getSkuId());
                jsonObject.put("upc", overseasLogisticsP1InfoDto.getGoodsList().get(j).getUpc());
                jsonObject.put("name", overseasLogisticsP1InfoDto.getGoodsList().get(j).getName());
                jsonObject.put("cny_name", overseasLogisticsP1InfoDto.getGoodsList().get(j).getCnyName());
                jsonObject.put("category", overseasLogisticsP1InfoDto.getGoodsList().get(j).getCategory());
                jsonObject.put("brand", overseasLogisticsP1InfoDto.getGoodsList().get(j).getBrand());
                jsonObject.put("spec", overseasLogisticsP1InfoDto.getGoodsList().get(j).getSpec());
                jsonObject.put("price_unit", overseasLogisticsP1InfoDto.getGoodsList().get(j).getPriceUnit());
                jsonObject.put("declared_price", overseasLogisticsP1InfoDto.getGoodsList().get(j).getDeclaredPrice());
                jsonObject.put("count", overseasLogisticsP1InfoDto.getGoodsList().get(j).getCount());
                jsonArray.add(jsonObject);
            }
            jso.put("goods_list", jsonArray);
        }
        jo.put("param", jso);
        logger.info(JSON.toJSONString(jo));
        String result = HttpUtil.doRequestPostString(JSON.toJSONString(jo), p1Url);
        JSONObject jsonObject = JSON.parseObject(result);
        if (jsonObject != null && jsonObject.get("code").equals(0)) {
            this.updateP2Status(overseasLogisticsP1InfoDto.getOverseaExpressNo(), OverseasLogisticsEnums.p2Status.FORECAST_SUCCESS.getCode());
            overseasLogisticsErrorService.updateHandingStatusByOverseaExpressNo(overseasLogisticsP1InfoDto.getOverseaExpressNo());
            return new DataOutput(CommonStatus.SUCCESS);
        }
        return new DataOutput(CommonStatus.SERVER_ERROR);

    }

    /**
     * 调用接口更新接口状态
     *
     * @param overseaExpressNo
     * @param p2Status
     */
    @Transactional
    public void updateP2Status(String overseaExpressNo, Integer p2Status) {
        repository.updateByWhere(Q.overseaExpressNo.eq(overseaExpressNo),
                it -> it.set(Q.p2Status, p2Status)
                        .set(Q.lastUpdateTime, new Date()));
    }

    /**
     * 邮客创建订单
     */
    @Transactional
    public void createOrder() {
        String imageUrl = headUrl;
        //String url = "http://t.yyox.com:1010/createOrder";
        //接口调用
        List<String> listTanks = queryFactory.select(Q.tanksNo).from(Q).where(Q.isDelete.eq(false).
                and(Q.p4Status.eq(OverseasLogisticsEnums.p4Status.NO_STOCK.getCode())
                        .and(Q.tanksNo.isNotNull()))).groupBy(Q.tanksNo).fetch();//合箱号
        if (listTanks != null && listTanks.size() > 0) {
            for (int i = 0; i < listTanks.size(); i++) {//根据和箱号循环发送请求
                QOverseasProductInfoModel qOverseasProductInfoModel = QOverseasProductInfoModel.overseasProductInfoModel;
                List<OverseasLogisticsP3InfoDto> list = queryFactory.select(qOverseasProductInfoModel).from(qOverseasProductInfoModel)
                        .leftJoin(Q).on(qOverseasProductInfoModel.overseaExpressNo.eq(Q.overseaExpressNo)).where(Q.isDelete.eq(false).
                                and(Q.p4Status.eq(OverseasLogisticsEnums.p4Status.NO_STOCK.getCode()).and(Q.tanksNo.eq(listTanks.get(i)))))
                        .fetch().stream().map(it -> {
                            OverseasLogisticsP3InfoDto overseasLogisticsP3InfoDto = new OverseasLogisticsP3InfoDto();
                            BeanUtils.copyProperties(it, overseasLogisticsP3InfoDto);
                            overseasLogisticsP3InfoDto.setWareHouseId("ORB");
                            overseasLogisticsP3InfoDto.setUsername(username);
                            overseasLogisticsP3InfoDto.setPassword(password);
                            List<OverseasLogisticsInfoModel>overseasLogisticsInfoModelList = repository.findAll(Q.overseaExpressNo.eq(it.getOverseaExpressNo()));
                            if (overseasLogisticsInfoModelList != null && overseasLogisticsInfoModelList.size()>0) {
                                BeanUtils.copyProperties(overseasLogisticsInfoModelList.get(0), overseasLogisticsP3InfoDto);
                            }
                            return overseasLogisticsP3InfoDto;

                        }).collect(Collectors.toList());

                //根据结果发送请求
                if (list != null && list.size() > 0) {
                    JSONObject js = new JSONObject();
                    JSONObject jso = new JSONObject();
                    jso.put("buyer_name", list.get(0).getBuyerName());
                    jso.put("buyer_idcard", list.get(0).getBuyerIdcard());
                    jso.put("buyer_idcard_frontend", imageUrl + list.get(0).getBuyerIdcardFrontend());
                    jso.put("buyer_idcard_backend", imageUrl + list.get(0).getBuyerIdcardBackend());
                    jso.put("buyer_mobile", list.get(0).getBuyerMobile());
                    jso.put("buyer_province", list.get(0).getBuyerProvince());
                    jso.put("buyer_city", list.get(0).getBuyerCity());
                    jso.put("buyer_district", list.get(0).getBuyerDistrict());
                    jso.put("buyer_adress", list.get(0).getBuyerAdress());
                    jso.put("buyer_zipcode", list.get(0).getBuyerZipcode());
                    jso.put("value_added", new JSONArray());
                    jso.put("warehouse_id", "ORB");
                    jso.put("username", username);
                    jso.put("password", password);
                    jso.put("customer_ref_no", list.get(0).getCustomerRefNo());
                    jso.put("api_order_type", "PKG");
                    jso.put("sender_name", list.get(0).getSenderName());
                    jso.put("sender_detailaddress", list.get(0).getSenderDetailaddress());
                    jso.put("sender_mobile", list.get(0).getSenderMobile());
                    jso.put("package_type", "ORG");
                    jso.put("client_create_order_date", list.get(0).getClientCreateOrderDateStr());

                    JSONArray jsonArray = new JSONArray();
                    for (int j = 0; j < list.size(); j++) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("sku_id", list.get(j).getSkuId());
                        jsonObject.put("upc", list.get(j).getUpc());
                        jsonObject.put("name", list.get(j).getName());
                        jsonObject.put("cny_name", list.get(j).getCnyName());
                        jsonObject.put("category", list.get(j).getCategory());
                        jsonObject.put("brand", list.get(j).getBrand());
                        jsonObject.put("spec", list.get(j).getSpec());
                        jsonObject.put("price_unit", list.get(j).getPriceUnit());
                        jsonObject.put("declared_price", list.get(j).getDeclaredPrice());
                        jsonObject.put("count", list.get(j).getCount());
                        jsonObject.put("oversea_express_no", list.get(j).getOverseaExpressNo());
                        jsonArray.add(jsonObject);
                    }
                    jso.put("goods_list", jsonArray);
                    js.put("param", jso);
                    logger.info("p3请求参数:{}",JSON.toJSONString(js));
                    //发送请求
                    JSONObject jsonObject = null;
                    try {
                        String result = HttpUtil.doRequestPostString(JSON.toJSONString(js), p3Url);
                        if (StringUtils.isNotBlank(result)){
                            jsonObject = JSON.parseObject(result);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (jsonObject != null && jsonObject.get("code").equals(0)) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        if (jsonObject1 != null) {
                            String transferId = jsonObject1.getString("transfer_id");
                            this.updateP4StatusByTanksNo(listTanks.get(i), transferId, OverseasLogisticsEnums.p4Status.STOCK_SUCCESS.getCode());
                        }
                    }
                }

            }

        }
        //合箱号为空的
        List<OverseasLogisticsP3InfoDto> list = repository.findAll(Q.isDelete.eq(false).and(Q.p4Status.eq(OverseasLogisticsEnums.p4Status.NO_STOCK.getCode())).and(Q.tanksNo.isNull()))
                .stream().map(it -> {
                    OverseasLogisticsP3InfoDto overseasLogisticsP3InfoDto = new OverseasLogisticsP3InfoDto();
                    BeanUtils.copyProperties(it, overseasLogisticsP3InfoDto);
                    overseasLogisticsP3InfoDto.setWareHouseId("ORB");
                    overseasLogisticsP3InfoDto.setUsername(username);
                    overseasLogisticsP3InfoDto.setPassword(password);
                    List<OverseasProductInfoDto> productInfoDtolList = overseasProductInfoService.findProductByNo(it.getOverseaExpressNo());
                    if (productInfoDtolList != null && productInfoDtolList.size() > 0) {
                        overseasLogisticsP3InfoDto.setGoodsList(productInfoDtolList);
                    }
                    return overseasLogisticsP3InfoDto;
                }).collect(Collectors.toList());

        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                JSONObject js = new JSONObject();
                JSONObject jso = new JSONObject();
                jso.put("buyer_name", list.get(i).getBuyerName());
                jso.put("buyer_idcard", list.get(i).getBuyerIdcard());
                jso.put("buyer_idcard_frontend", imageUrl + list.get(i).getBuyerIdcardFrontend());
                jso.put("buyer_idcard_backend", imageUrl + list.get(i).getBuyerIdcardBackend());
                jso.put("buyer_mobile", list.get(i).getBuyerMobile());
                jso.put("buyer_province", list.get(i).getBuyerProvince());
                jso.put("buyer_city", list.get(i).getBuyerCity());
                jso.put("buyer_district", list.get(i).getBuyerDistrict());
                jso.put("buyer_adress", list.get(i).getBuyerAdress());
                jso.put("buyer_zipcode", list.get(i).getBuyerZipcode());
                jso.put("value_added", new JSONArray());
                jso.put("warehouse_id", "ORB");
                jso.put("username", username);
                jso.put("password", password);
                jso.put("customer_ref_no", list.get(i).getCustomerRefNo());
                jso.put("api_order_type", "PKG");
                jso.put("sender_name", list.get(i).getSenderName());
                jso.put("sender_detailaddress", list.get(i).getSenderDetailaddress());
                jso.put("sender_mobile", list.get(i).getSenderMobile());
                jso.put("package_type", "ORG");
                jso.put("client_create_order_date", list.get(i).getClientCreateOrderDateStr());
                if (list.get(i).getGoodsList() != null && list.get(i).getGoodsList().size() > 0) {
                    JSONArray jsonArray = new JSONArray();
                    for (int j = 0; j < list.get(i).getGoodsList().size(); j++) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("sku_id", list.get(i).getGoodsList().get(j).getSkuId());
                        jsonObject.put("upc", list.get(i).getGoodsList().get(j).getUpc());
                        jsonObject.put("name", list.get(i).getGoodsList().get(j).getName());
                        jsonObject.put("cny_name", list.get(i).getGoodsList().get(j).getCnyName());
                        jsonObject.put("category", list.get(i).getGoodsList().get(j).getCategory());
                        jsonObject.put("brand", list.get(i).getGoodsList().get(j).getBrand());
                        jsonObject.put("spec", list.get(i).getGoodsList().get(j).getSpec());
                        jsonObject.put("price_unit", list.get(i).getGoodsList().get(j).getPriceUnit());
                        jsonObject.put("declared_price", list.get(i).getGoodsList().get(j).getDeclaredPrice());
                        jsonObject.put("count", list.get(i).getGoodsList().get(j).getCount());
                        jsonObject.put("oversea_express_no", list.get(i).getGoodsList().get(j).getOverseaExpressNo());
                        jsonArray.add(jsonObject);
                    }
                    jso.put("goods_list", jsonArray);
                }
                js.put("param", jso);
                logger.info(JSON.toJSONString(js));
                String result = HttpUtil.doRequestPostString(JSON.toJSONString(js), p3Url);
                JSONObject jsonObject = JSON.parseObject(result);
                if (jsonObject != null && jsonObject.get("code").equals(0)) {
                    JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                    if (jsonObject1 != null) {
                        String transferId = jsonObject1.getString("transfer_id");
                        this.updateP4Status(list.get(i).getOverseaExpressNo(), transferId, OverseasLogisticsEnums.p4Status.STOCK_SUCCESS.getCode());
                    }
                }
                logger.info("返回结果:{}", result);

            }
        }

        //查询P3接口待发送请求
    /*    List<OverseasLogisticsP3InfoDto> list = repository.findAll(Q.isDelete.eq(false).and(Q.p4Status.eq(OverseasLogisticsEnums.p4Status.NO_STOCK.getCode())))
                .stream().map(it -> {
                    OverseasLogisticsP3InfoDto overseasLogisticsP3InfoDto = new OverseasLogisticsP3InfoDto();
                    BeanUtils.copyProperties(it, overseasLogisticsP3InfoDto);
                    overseasLogisticsP3InfoDto.setWareHouseId("ORB");
                    overseasLogisticsP3InfoDto.setUsername("Poyyox@yyox.com");
                    overseasLogisticsP3InfoDto.setPassword("8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92");
                    List<OverseasProductInfoDto> productInfoDtolList = overseasProductInfoService.findProductByNo(it.getOverseaExpressNo());
                    if (productInfoDtolList != null && productInfoDtolList.size() > 0) {
                        overseasLogisticsP3InfoDto.setGoodsList(productInfoDtolList);
                    }
                    return overseasLogisticsP3InfoDto;
                }).collect(Collectors.toList());
        if (list != null && list.size() > 0) {

            for (int i = 0; i < list.size(); i++) {
                JSONObject js = new JSONObject();
                JSONObject jso = new JSONObject();
                jso.put("buyer_name", list.get(i).getBuyerName());
                jso.put("buyer_idcard", list.get(i).getBuyerIdcard());
                jso.put("buyer_idcard_frontend", imageUrl + list.get(i).getBuyerIdcardFrontend());
                jso.put("buyer_idcard_backend", imageUrl + list.get(i).getBuyerIdcardBackend());
                jso.put("buyer_mobile", list.get(i).getBuyerMobile());
                jso.put("buyer_province", list.get(i).getBuyerProvince());
                jso.put("buyer_city", list.get(i).getBuyerCity());
                jso.put("buyer_district", list.get(i).getBuyerDistrict());
                jso.put("buyer_adress", list.get(i).getBuyerAdress());
                jso.put("buyer_zipcode", list.get(i).getBuyerZipcode());
                jso.put("value_added", new JSONArray());
                jso.put("warehouse_id", "ORB");
                jso.put("username", "Poyyox@yyox.com");
                jso.put("password", "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92");
                jso.put("customer_ref_no", list.get(i).getCustomerRefNo());
                jso.put("api_order_type", "PKG");
                jso.put("sender_name", list.get(i).getSenderName());
                jso.put("sender_detailaddress", list.get(i).getSenderDetailaddress());
                jso.put("sender_mobile", list.get(i).getSenderMobile());
                jso.put("package_type", "ORG");
                jso.put("client_create_order_date", list.get(i).getClientCreateOrderDateStr());
                if (list.get(i).getGoodsList() != null && list.get(i).getGoodsList().size() > 0) {
                    JSONArray jsonArray = new JSONArray();
                    for (int j = 0; j < list.get(i).getGoodsList().size(); j++) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("sku_id", list.get(i).getGoodsList().get(j).getSkuId());
                        jsonObject.put("upc", list.get(i).getGoodsList().get(j).getUpc());
                        jsonObject.put("name", list.get(i).getGoodsList().get(j).getName());
                        jsonObject.put("cny_name", list.get(i).getGoodsList().get(j).getCnyName());
                        jsonObject.put("category", list.get(i).getGoodsList().get(j).getCategory());
                        jsonObject.put("brand", list.get(i).getGoodsList().get(j).getBrand());
                        jsonObject.put("spec", list.get(i).getGoodsList().get(j).getSpec());
                        jsonObject.put("price_unit", list.get(i).getGoodsList().get(j).getPriceUnit());
                        jsonObject.put("declared_price", list.get(i).getGoodsList().get(j).getDeclaredPrice());
                        jsonObject.put("count", list.get(i).getGoodsList().get(j).getCount());
                        jsonObject.put("oversea_express_no", list.get(i).getGoodsList().get(j).getOverseaExpressNo());
                        jsonArray.add(jsonObject);
                    }
                    jso.put("goods_list", jsonArray);
                }
                js.put("param", jso);
                logger.info(JSON.toJSONString(js));
                String result = HttpUtil.doRequestPostString(JSON.toJSONString(js), url);
                JSONObject jsonObject = JSON.parseObject(result);
                if (jsonObject != null && jsonObject.get("code").equals(0)) {
                    JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                    if (jsonObject1 != null) {
                        String transferId = jsonObject1.getString("transfer_id");
                        this.updateP4Status(list.get(i).getOverseaExpressNo(), transferId, OverseasLogisticsEnums.p4Status.STOCK_SUCCESS.getCode());
                    }
                }
                logger.info("返回结果:{}", result);

            }
        }*/
    }

    /**
     * 描述: 入库状态(入库回调)
     *
     * @param
     * @return
     * @auther: Kien
     */
    @Transactional
    public JSONObject warehouseCallback(HttpServletRequest request) {
        // TODO 获取请求ip地址 BaseUtils
        JSONObject result = new JSONObject();
        StringBuilder sb = new StringBuilder();
        BufferedReader br = null;
        try {
            // 1.获取请求参数
            br = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            JSONObject jsonObject = JSON.parseObject(sb.toString()); // 将请求参数json化
            Object param = jsonObject.get("param");
            if(sb != null && sb.length() != 0) {
                JSONObject jsonObject1 = JSON.toJSONObject(param);
                WarehouseCallbackVo warehouseCallbackVo = JacksonUtils.fromJson(jsonObject1.toJSONString(), WarehouseCallbackVo.class);
                DataOutput dataOutput = updateOverseasLogisticsP2Status(warehouseCallbackVo);
                if(dataOutput.getStatus().equals("0")){
                    result.put("code", 0);
                    result.put("message", null);
                    return result;
                } else {
                    result.put("code", 0);
                    result.put("message", dataOutput.getMessage());
                    return result;
                }
            }
            result.put("code", 0);
            result.put("message", null);
            return result;
        } catch (Exception e) {
            logger.error("入库回调异常", e);
            result.put("code", 1);
            result.put("message", CommonStatus.SERVER_ERROR.getMessage());
            return result;
        }
    }

    /**
     * 邮客创建订单i
     */
    public DataOutput createOrderById(String id) {
        String imageUrl = headUrl;
       // String url = "http://t.yyox.com:1010/createOrder";
        //查询P3接口待发送请求
        OverseasLogisticsInfoModel overseasLogisticsInfoModel = repository.findById(id);
        OverseasLogisticsP3InfoDto overseasLogisticsP3InfoDto = new OverseasLogisticsP3InfoDto();
        if (overseasLogisticsInfoModel != null) {
            BeanUtils.copyProperties(overseasLogisticsInfoModel, overseasLogisticsP3InfoDto);
            overseasLogisticsP3InfoDto.setWareHouseId("ORB");
            overseasLogisticsP3InfoDto.setUsername(username);
            overseasLogisticsP3InfoDto.setPassword(password);
            List<OverseasProductInfoDto> productInfoDtolList = overseasProductInfoService.findProductByNo(overseasLogisticsInfoModel.getOverseaExpressNo());
            if (productInfoDtolList != null && productInfoDtolList.size() > 0) {
                overseasLogisticsP3InfoDto.setGoodsList(productInfoDtolList);
            }
        }
        JSONObject js = new JSONObject();
        JSONObject jso = new JSONObject();
        jso.put("buyer_name", overseasLogisticsP3InfoDto.getBuyerName());
        jso.put("buyer_idcard", overseasLogisticsP3InfoDto.getBuyerIdcard());
        jso.put("buyer_idcard_frontend", imageUrl + overseasLogisticsP3InfoDto.getBuyerIdcardFrontend());
        jso.put("buyer_idcard_backend", imageUrl + overseasLogisticsP3InfoDto.getBuyerIdcardBackend());
        jso.put("buyer_mobile", overseasLogisticsP3InfoDto.getBuyerMobile());
        jso.put("buyer_province", overseasLogisticsP3InfoDto.getBuyerProvince());
        jso.put("buyer_city", overseasLogisticsP3InfoDto.getBuyerCity());
        jso.put("buyer_district", overseasLogisticsP3InfoDto.getBuyerDistrict());
        jso.put("buyer_adress", overseasLogisticsP3InfoDto.getBuyerAdress());
        jso.put("buyer_zipcode", overseasLogisticsP3InfoDto.getBuyerZipcode());
        jso.put("value_added", new JSONArray());
        jso.put("warehouse_id", "ORB");
        jso.put("username", username);
        jso.put("password", password);
        jso.put("customer_ref_no", overseasLogisticsP3InfoDto.getCustomerRefNo());
        jso.put("api_order_type", "PKG");
        jso.put("sender_name", overseasLogisticsP3InfoDto.getSenderName());
        jso.put("sender_detailaddress", overseasLogisticsP3InfoDto.getSenderDetailaddress());
        jso.put("sender_mobile", overseasLogisticsP3InfoDto.getSenderMobile());
        jso.put("package_type", "ORG");
        jso.put("client_create_order_date", overseasLogisticsP3InfoDto.getClientCreateOrderDateStr());
        if (overseasLogisticsP3InfoDto.getGoodsList() != null && overseasLogisticsP3InfoDto.getGoodsList().size() > 0) {
            JSONArray jsonArray = new JSONArray();
            for (int j = 0; j < overseasLogisticsP3InfoDto.getGoodsList().size(); j++) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("sku_id", overseasLogisticsP3InfoDto.getGoodsList().get(j).getSkuId());
                jsonObject.put("upc", overseasLogisticsP3InfoDto.getGoodsList().get(j).getUpc());
                jsonObject.put("name", overseasLogisticsP3InfoDto.getGoodsList().get(j).getName());
                jsonObject.put("cny_name", overseasLogisticsP3InfoDto.getGoodsList().get(j).getCnyName());
                jsonObject.put("category", overseasLogisticsP3InfoDto.getGoodsList().get(j).getCategory());
                jsonObject.put("brand", overseasLogisticsP3InfoDto.getGoodsList().get(j).getBrand());
                jsonObject.put("spec", overseasLogisticsP3InfoDto.getGoodsList().get(j).getSpec());
                jsonObject.put("price_unit", overseasLogisticsP3InfoDto.getGoodsList().get(j).getPriceUnit());
                jsonObject.put("declared_price", overseasLogisticsP3InfoDto.getGoodsList().get(j).getDeclaredPrice());
                jsonObject.put("count", overseasLogisticsP3InfoDto.getGoodsList().get(j).getCount());
                jsonObject.put("oversea_express_no", overseasLogisticsP3InfoDto.getGoodsList().get(j).getOverseaExpressNo());
                jsonArray.add(jsonObject);
            }
            jso.put("goods_list", jsonArray);
        }
        js.put("param", jso);
        logger.info(JSON.toJSONString(js));
        String result = HttpUtil.doRequestPostString(JSON.toJSONString(js), p3Url);
        JSONObject jsonObject = JSON.parseObject(result);
        if (jsonObject != null && jsonObject.get("code").equals(0)) {
            JSONObject jsonObject1 = jsonObject.getJSONObject("data");
            if (jsonObject1 != null) {
                String transferId = jsonObject1.getString("transfer_id");
                this.updateP4Status(overseasLogisticsP3InfoDto.getOverseaExpressNo(), transferId, OverseasLogisticsEnums.p4Status.STOCK_SUCCESS.getCode());
            }
            return new DataOutput(CommonStatus.SUCCESS);
        }
        logger.info("返回结果:{}", result);
        return new DataOutput(CommonStatus.SERVER_ERROR);
    }

    /**
     * 描述: 接受转运状态推送
     *
     * @param request
     * @return
     * @auther: Kien
     */
    @Transactional
    public JSONObject transferStatusCallback(HttpServletRequest request) {
        // TODO 获取请求ip地址 BaseUtils
        JSONObject result = new JSONObject();
        StringBuilder sb = new StringBuilder();
        BufferedReader br = null;
        try {
            // 1.获取请求参数
            br = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            if (sb != null && sb.length() != 0) {
                JSONObject jsonObject = JSON.parseObject(sb.toString()); // 将请求参数json化
                Object param = jsonObject.get("param");
                JSONObject jsonObject1 = JSON.toJSONObject(param);
                TransferStatusCallbackVo transferStatusCallbackVo = JacksonUtils.fromJson(jsonObject1.toJSONString(), TransferStatusCallbackVo.class);
                if (transferStatusCallbackVo != null) {
                    DataOutput dataOutput = updateOverseasLogisticsP4Status(transferStatusCallbackVo);
                    if(dataOutput.getStatus().equals("0")){
                        result.put("code", 0);
                        result.put("message", null);
                    } else {
                        result.put("code", 1);
                        result.put("message", dataOutput.getMessage());
                    }
                } else {
                    result.put("code", 1);
                    result.put("message", CommonStatus.SERVER_ERROR.getMessage());
                }
                return result;
            }
            result.put("code", 0);
            result.put("message", null);
            return result;
        } catch (Exception e) {
            logger.error("转运状态回调异常", e);
            result.put("code", 1);
            result.put("message", CommonStatus.SERVER_ERROR.getMessage());
            return result
                    ;
        }
    }

    /**
     * 描述: 转运状态推送回调
     *
     * @param
     * @return
     * @auther: Kien
     */
    @Transactional
    public DataOutput updateOverseasLogisticsP4Status(TransferStatusCallbackVo transferStatusCallbackVo) {
        String transfer_id = transferStatusCallbackVo.getTransfer_id();
        if (base.isBlank(transfer_id)) {
            return new DataOutput(CommonStatus.BAD_REQUEST);
        }
        List<OverseasLogisticsInfoModel> all = repository.findAll(Q.transferId.eq(transfer_id));
        if (CollectionUtils.isEmpty(all)) {
            return new DataOutput(CommonStatus.BAD_REQUEST);
        }
        int i = 0;
        for(OverseasLogisticsInfoModel overseasLogisticsInfoModel: all){
            int j = repository.updateByWhere(
                    PredicateBuilder.conjunction().and(()->Q.id.eq(overseasLogisticsInfoModel.getId())).get(),
//                Q.transferId.eq(transfer_id),
                    it ->
                            it.set(Q.p4Status, Integer.valueOf(transferStatusCallbackVo.getStatus()))
                                    .set(Q.customerRefNo, transferStatusCallbackVo.getCustomer_ref_no())
                                    .set(Q.overseaInTime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getOversea_in_time()))
                                    .set(Q.validateIdcardTime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getValidate_idcard_time()))
                                    .set(Q.pickupTime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getPickup_time()))
                                    .set(Q.overseaOutTime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getOversea_out_time()))
                                    .set(Q.palletTime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getPallet_time()))
                                    .set(Q.waitForTransferTime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getWait_for_transfer_time()))
                                    .set(Q.overseaOnTransferTime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getOversea_on_transfer_time()))
                                    .set(Q.inlandInTime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getInland_in_time()))
                                    .set(Q.taketime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getTake_time()))
                                    .set(Q.customTime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getCustom_time()))
                                    .set(Q.examineTime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getExamine_time()))
                                    .set(Q.inlandOutTime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getInland_out_time()))
                                    .set(Q.buyerSignTime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getBuyer_sign_time()))
                                    .set(Q.inlandExpressId, transferStatusCallbackVo.getInland_express_id())
                                    .set(Q.inlandExpressNo, transferStatusCallbackVo.getInland_express_no())
                                    .set(Q.weight, transferStatusCallbackVo.getWeight())
                                    .set(Q.volume, transferStatusCallbackVo.getVolume())
                                    .set(Q.totalfee, transferStatusCallbackVo.getTotalfee())
                                    .set(Q.airTakeOff, transferStatusCallbackVo.getAir_take_off())
                                    .set(Q.airlines, transferStatusCallbackVo.getAirlines())
                                    .set(Q.flight, transferStatusCallbackVo.getFlight())
                                    .set(Q.masterWaybillNo, transferStatusCallbackVo.getMaster_waybill_no())
                                    .set(Q.apiOrderType, transferStatusCallbackVo.getApi_order_type())
            );
            i += j;
        }

        if (i == 0) {
            return new DataOutput(CommonStatus.SERVER_ERROR);
        } else {
            return new DataOutput();
        }
    }

//    @Transactional
//    public DataOutput uodateP4Status(String transfer_id, TransferStatusCallbackVo transferStatusCallbackVo) {
//        OverseasLogisticsInfoModel overseasLogisticsInfoModel = repository.findOne(Q.transferId.eq(transfer_id));
//        if(overseasLogisticsInfoModel == null){
//            return new DataOutput(CommonStatus.BAD_REQUEST);
//        }
//        int i = repository.updateByWhere(
//                PredicateBuilder.conjunction().and(()->Q.id.eq(overseasLogisticsInfoModel.getId())).get(),
////                Q.transferId.eq(transfer_id),
//                it ->
//                it.set(Q.p4Status, Integer.valueOf(transferStatusCallbackVo.getStatus()))
//                        .set(Q.customerRefNo, transferStatusCallbackVo.getCustomer_ref_no())
//                        .set(Q.overseaInTime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getOversea_in_time()))
//                        .set(Q.validateIdcardTime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getValidate_idcard_time()))
//                        .set(Q.pickupTime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getPickup_time()))
//                        .set(Q.overseaOutTime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getOversea_out_time()))
//                        .set(Q.palletTime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getPallet_time()))
//                        .set(Q.waitForTransferTime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getWait_for_transfer_time()))
//                        .set(Q.overseaOnTransferTime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getOversea_on_transfer_time()))
//                        .set(Q.inlandInTime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getInland_in_time()))
//                        .set(Q.taketime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getTake_time()))
//                        .set(Q.customTime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getCustom_time()))
//                        .set(Q.examineTime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getExamine_time()))
//                        .set(Q.inlandOutTime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getInland_out_time()))
//                        .set(Q.buyerSignTime, DateUtils.parseDateMilliFormat(transferStatusCallbackVo.getBuyer_sign_time()))
//                        .set(Q.inlandExpressId, transferStatusCallbackVo.getInland_express_id())
//                        .set(Q.inlandExpressNo, transferStatusCallbackVo.getInland_express_no())
//                        .set(Q.weight, transferStatusCallbackVo.getWeight())
//                        .set(Q.volume, transferStatusCallbackVo.getVolume())
//                        .set(Q.totalfee, transferStatusCallbackVo.getTotalfee())
//                        .set(Q.airTakeOff, transferStatusCallbackVo.getAir_take_off())
//                        .set(Q.airlines, transferStatusCallbackVo.getAirlines())
//                        .set(Q.flight, transferStatusCallbackVo.getFlight())
//                        .set(Q.masterWaybillNo, transferStatusCallbackVo.getMaster_waybill_no())
//                        .set(Q.apiOrderType, transferStatusCallbackVo.getApi_order_type())
//        );
//        if(i == 0){
//            return new DataOutput(CommonStatus.SERVER_ERROR);
//        } else {
//            return new DataOutput();
//        }
//    }

    /**
     * 描述: 入库回调修改
     *
     * @param
     * @return
     * @auther: Kien
     */
    @Transactional
    public DataOutput updateOverseasLogisticsP2Status(WarehouseCallbackVo warehouseCallbackVo) {
        String overseaExpressNo = warehouseCallbackVo.getOversea_express_no(); // 发货快递编号
        Integer status = warehouseCallbackVo.getStatus(); // 入库状态
        if (base.parametersIsBlank(overseaExpressNo)) {
            return new DataOutput(CommonStatus.BAD_REQUEST);
        }
        // 快递编号时间是当前时间的往前推180天，和当前时间的后一天
        Date pastDate = DateUtils.getPastDate(180); // 当前日期的前180天
        Date nextDate = DateUtils.getPastDate(-1); // 明天
        // 根据发货快递编号，查询(必须是180天以内的)
        OverseasLogisticsInfoModel overseasLogisticsInfoModel = repository.findOne(Q.overseaExpressNo.eq(overseaExpressNo).and(Q.createTime.before(nextDate)).and(Q.createTime.after(pastDate)));
        if (overseasLogisticsInfoModel != null) {
            // 修改状态值
            int i = repository.updateByWhere(Q.id.eq(overseasLogisticsInfoModel.getId()), it -> it.set(Q.p2Status, Integer.valueOf(status)));
            if (i == 0) {
                return new DataOutput(CommonStatus.SERVER_ERROR);
            } else {
                return new DataOutput();
            }
        } else {
            // 如果没有查询到，需要将这条信息写入到数据库或者status不等于2的
            OverseasLogisticsErrorModel overseasLogisticsErrorModel = new OverseasLogisticsErrorModel();
            overseasLogisticsErrorModel.setClientIdentifier(warehouseCallbackVo.getClient_identifier());
            overseasLogisticsErrorModel.setInboundWeight(warehouseCallbackVo.getInbound_weight().toString());
            overseasLogisticsErrorModel.setOverseaExpressNo(warehouseCallbackVo.getOversea_express_no());
            overseasLogisticsErrorModel.setStatus(Integer.valueOf(warehouseCallbackVo.getStatus()));
            overseasLogisticsErrorModel.setWareHouseId(warehouseCallbackVo.getWare_house_id());
            if(overseasLogisticsInfoModel == null){
                // 异常信息来源，是因为我们没有导入数据库
                overseasLogisticsErrorModel.setStatusError(OverseasLogisticsEnums.STATUS_ERROR.NO_EXIST.getCode());
            } else {
                // 异常信息来源，是没有推送预报
                overseasLogisticsErrorModel.setStatusError(OverseasLogisticsEnums.STATUS_ERROR.NO_PUSH.getCode());
                overseasLogisticsErrorModel.setOverseasLogisticsInfoId(Long.valueOf(overseasLogisticsInfoModel.getId()));
            }
            overseasLogisticsErrorModel.setHandlingStatus(OverseasLogisticsEnums.HANDLING_STATUS.UNTREATED.getCode()); // 未处理
            overseasLogisticsErrorModel.setCreateTime(new Date());
            DataOutput dataOutput = overseasLogisticsErrorService.saveOverseasLogisticsError(overseasLogisticsErrorModel);
            return dataOutput;
        }
    }


    /**
     * 调用接口更新接口状态
     *
     * @param overseaExpressNo
     * @param transferId
     * @param p4Status
     */
    @Transactional
    public void updateP4Status(String overseaExpressNo, String transferId, Integer p4Status) {
        if (StringUtils.isNotBlank(transferId)) {
            repository.updateByWhere(Q.overseaExpressNo.eq(overseaExpressNo),
                    it -> it.set(Q.transferId, transferId)
                            .set(Q.p4Status, p4Status)
                            .set(Q.lastUpdateTime, new Date()));
        }
    }

    /**
     * 调用接口更新接口状态
     *
     * @param tanks
     * @param transferId
     * @param p4Status
     */
    @Transactional
    public void updateP4StatusByTanksNo(String tanks, String transferId, Integer p4Status) {
        if (StringUtils.isNotBlank(transferId)) {
            repository.updateByWhere(Q.tanksNo.eq(tanks).and(Q.p4Status.eq(OverseasLogisticsEnums.p4Status.NO_STOCK.getCode())
                            .and(Q.tanksNo.isNotNull())),
                    it -> it.set(Q.transferId, transferId)
                            .set(Q.p4Status, p4Status)
                            .set(Q.lastUpdateTime, new Date()));
        }
    }

}
